package com.woniuxy.vuecli.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.woniuxy.vuecli.entity.ResponseResult;
import com.woniuxy.vuecli.entity.VerifyCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author author
 * @Create 2024-02-20 9:33
 */
@Slf4j
@RestController
public class VerifyCodeController {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/verifycode/create")
    public ResponseResult<VerifyCode> create(HttpServletResponse response) throws IOException {
        //生成验证码
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 20);
        //获取验证码字符串
        String verifycode = captcha.getCode();
        log.info("verifycode={}",verifycode);
        //获取图片二进制文件的base64编码
        String imageBase64Data = ((LineCaptcha) captcha).getImageBase64Data();
        log.info("imageBase64Data={}",imageBase64Data);
        String verifycodeid = UUID.randomUUID().toString();
        //存入redis-key(verifycodeid)-value(verifycode),设置过期时间
        //实际项目，同一组数据，key命名规范，统一前缀:唯一ID，student:1  student:1  employee:1  employee:2
        //verifycodeid:xxxx-xxx-xxx-xxxx  verifycodeid:xxxx-xxx-xxx-xxxx
        redisTemplate.opsForValue().set("verifycodeid:"+verifycodeid, verifycode, 60, TimeUnit.SECONDS);
        return new ResponseResult<>(200,"ok",new VerifyCode(imageBase64Data,"verifycodeid:"+verifycodeid));

    }


//    @RequestMapping("/verifycode/create")
//    public void create(HttpServletResponse response) throws IOException {
//        //生成验证码
//        ICaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 20);
//        //获取验证码字符串
//        log.info("verifycode={}",captcha.getCode());
//        String imageBase64 = ((LineCaptcha) captcha).getImageBase64();
//        String imageBase64Data = ((LineCaptcha) captcha).getImageBase64Data();
//        log.info("imageBase64={}",imageBase64);
//        log.info("imageBase64Data={}",imageBase64Data);
//        //验证码如何存储:Session(不好用)，通过响应头存到前端localstorage(不安全，容易修改，验证没有意义)
//        //学习Redis缓存技术，将验证码存入redis中
//        //通过字节流响应给用户
////        captcha.write(response.getOutputStream());
//        //除了图片本身还要UUID,前后端分离要使用统一响应体
//
//    }
}
